<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>
        {{$t('report.staffCategoryChart.title1')}}
        <el-popover trigger="hover">
          {{ $t('report.staffCategoryChart.title2') }}<br />
          {{ $t('report.staffCategoryChart.title3') }}<br />
          {{ $t('report.staffCategoryChart.title4') }}<br />
          {{ $t('report.staffCategoryChart.title5') }}<br />
          {{ $t('report.staffCategoryChart.title6') }}<br />
          {{ $t('report.staffCategoryChart.title7') }}<br />
          {{ $t('report.staffCategoryChart.title8') }}<br />
          <stats-popover-icon slot="reference"></stats-popover-icon>
        </el-popover>
      </h3>
      
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="ignoreDeleted" @input="chooseCategoryDeleted">{{$t('report.staffEventTable.title2')}}</base-checkbox>
      </div>
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="categoryIgnoreNull" @input="chooseCategoryIgnore">{{$t('report.staffCategoryChart.text2')}}</base-checkbox>
      </div>

      <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child collapse multiple :value="tag" @input="chooseCategoryTeam" :fetch-func="fetchTeam"/>
     
      <div class="stats-form-group">
        <!-- <div id="staff-date-range" class="stats-form-daterange">
          <span>{{categoryStartTime}} - {{categoryEndTime}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>
    <div class="stats-panel-body">
      <div style="text-align: center;">
        <div class="stats-btn-group">
          <button type="button" :class="{'stats-checked': categoryType == $t('common.tabs.event')}" @click="chooseCategoryType($t('common.tabs.event'))">{{ $t('common.tabs.event') }}</button>
          <button type="button" :class="{'stats-checked': categoryType == $t('common.base.degree')}" @click="chooseCategoryType($t('common.base.degree'))">{{$t('common.base.degree')}}</button>
          <button type="button" :class="{'stats-checked': categoryType == $t('report.staffCategoryChart.title9')}" @click="chooseCategoryType($t('report.staffCategoryChart.title9'))">{{$t('report.staffCategoryChart.title9')}}</button>
        </div>
      </div>
      <div class="category-chart-wrap">
        <div id="category"></div>
        <stats-chart-empty v-if="categoryEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
      </div>
      <div class="stats-staff-category-wrap" v-if="showTable">
        <div class="stats-table-header">
           <h3>{{ $t('report.stationTable.title2') }}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button>          
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div>
          <el-table :data="page.list" class="stats-table">

            <el-table-column :label="$t('common.base.serialNumber')" prop="eventNo" width="150px" :show-overflow-tooltip="false">
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.eventNo" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row)">{{scope.row.eventNo}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="cusName"></el-table-column>
            <el-table-column :label="$t('common.label.eventType')" prop="templateName" width="180px"></el-table-column>
              
            <template v-if="categoryType == $t('common.base.degree')">
              <el-table-column :label="$t('common.base.degree')" prop="degree" width="100px"></el-table-column>
            </template>

            <template v-if="categoryType == $t('report.staffCategoryChart.title9')">
              <el-table-column :label="$t('task.detail.components.respondTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.acceptUsedTime)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.detail.components.workTime')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.workUsedTime)}}
                </template>
              </el-table-column>
              <el-table-column :label="$t('event.list.text8')" width="180px">
                <template slot-scope="scope">
                  {{formatterTime(scope.row.finishUsedTime)}}
                </template>
              </el-table-column>
            </template>

            <el-table-column :label="$t('common.base.status')" width="120px">
              <template slot-scope="scope">
                {{formatState(scope.row.state)}}
              </template>
            </el-table-column>
            
            <el-table-column :label="$t('common.label.principalName')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.executorName }}
                </template>
              </template>
            </el-table-column>

            <el-table-column :label="$t('common.base.createUser')" width="120px">
              <template slot-scope="scope">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.createUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{ scope.row.createUserName }}
                </template>
              </template>
            </el-table-column>
            
            <el-table-column :label="$t('common.base.createTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.createTime | fmt}}
              </template>
            </el-table-column>
            <el-table-column :label="$t('common.label.finishTime')" width="180px">
              <template slot-scope="scope">
                {{scope.row.completeTime | fmt}}
              </template>
            </el-table-column>

          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
import { isOpenData,openAccurateTab  } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';
import http from 'src/util/HttpUtil';
import qs from 'src/util/querystring';

import echarts from 'packages/Echarts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import Loading from 'packages/BaseLoading';
import BaseCheckbox from 'packages/BaseCheckbox.vue';
import SampleTooltip from 'packages/SampleTooltip'
import { checkButtonDisplayed } from '@src/util/dom';

import { getThemeColor } from '@src/util/business/color'
import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

const USER_EVENT_LEGEND = [t('common.base.add'), t('common.base.finish')];
const USER_EVENT_OBJ = { [t('common.base.add')]: 'count', [t('common.base.finish')]: 'eCount' }
const USER_EVENT_COLOR = ['#6da9e7', '#48e8ab'];

const USER_DEGREE_LEGEND = [ t('common.base.satisfactionDegree.0'), t('common.base.satisfactionDegree.1'),t('common.base.satisfactionDegree.2'),t('common.base.satisfactionDegree.3'),t('common.base.satisfactionDegree.4')];
const USER_DEGREE_OBJ = { [t('common.base.satisfactionDegree.1')]: t('common.base.satisfactionDegree.1'), [t('common.base.satisfactionDegree.0')]: t('common.base.satisfactionDegree.0'), [t('common.base.satisfactionDegree.2')]: t('common.base.satisfactionDegree.2'), [t('common.base.satisfactionDegree.3')]: t('common.base.satisfactionDegree.3'), [t('common.base.satisfactionDegree.4')]: t('common.base.satisfactionDegree.0')}
const USER_DEGREE_COLOR = [ getThemeColor(),'#48e8ab', '#6da9e7', '#ffdd92', '#f6903d'];

const USER_EFFICIENCY_LEGEND = [t('report.common.averageTime.0'), t('report.common.averageTime.1'), t('report.common.averageTime.2')];
const USER_EFFICIENCY_OBJ =  { [t('report.common.averageTime.3')]: 'AverageAcceptUsedTime', [t('report.common.averageTime.4')]: 'AverageTaskUsedTime', [t('report.common.averageTime.1')]: 'AverageWorkUsedTime' }
const USER_EFFICIENCY_COLOR = ['#48e8ab', '#6da9e7', '#ffdd92'];

let category = null;

export default {
  name: 'staff-category-chart',
  props: ['evaluateConfig', 'chartType'],
  data(){
    return {
      isFirst: true,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tag: [],
      sort: '',
      categoryType: t('common.tabs.event'),
      categoryData: {},
      categoryIgnoreNull: true,
      categoryStartTime: '',
      categoryEndTime: '',
      categoryTeamId: '',
      categoryEmpty: false,

      showTable: false,
      model: {
        pageNum: 1,
        userId: '',
        selectType: ''
      },
      page: {},
      ignoreDeleted: true
    }
  },
  computed: {
    hasStar(){
      return this.evaluateConfig.useStarEvaluate;
    },
    hasTag(){
      return this.evaluateConfig.useTagEvaluate;
    },
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    }
  },
  methods: {
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    exportAllData(){
      const { categoryStartTime, categoryEndTime } = this
      let model = {
        createTimeStart: categoryStartTime,
        createTimeEnd: categoryEndTime,
        // executor: this.model.userId,
        tagId: this.categoryTeamId,
        timeType: 3,
        pageSize: 0,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted,
      };

      if (this.categoryType == t('common.base.degree')) model.degree = 'all';

      if(this.categoryType == t('report.staffCategoryChart.title9')) model.isEfficial = true;
    
      window.location.href = `/event/sum/personal/listExport?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportTrack(isExportAll) {
      const tab = ({
        [t('common.tabs.event')]: 'EVENT',
        [t('common.base.degree')]: 'SATISFACTION',
        [t('report.staffCategoryChart.title9')]: 'EFFICIENCY',
      })[this.categoryType]
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.chartType,
        tab
      }, '*')
    },
    exportData(){
      const { categoryStartTime, categoryEndTime } = this
      let model = {
        createTimeStart: categoryStartTime,
        createTimeEnd: categoryEndTime,
        executor: this.model.userId,
        tagId: this.categoryTeamId,
        timeType: this.model.timeType,
        pageSize: 0,
        ignoreNull: this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted,
      };

      if (this.categoryType == t('common.base.degree')) model.degree = this.model.degree;

      if(this.categoryType == t('report.staffCategoryChart.title9')) model.isEfficial = true;

      window.location.href = `/event/sum/personal/listExport?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `eventView_${ row.id}`, 
      //   title: `事件${row.eventNo}`, 
      //   close: true, 
      //   url: `/event/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: row.id,
        titleKey: row.eventNo,
        fromId
      })
    },
    fetchTableData(){
      const { categoryStartTime, categoryEndTime } = this
      let model = {
        createTimeStart: categoryStartTime,
        createTimeEnd: categoryEndTime,
        tagId: this.categoryTeamId,
        executor: this.model.userId,
        timeType: this.model.timeType,
        pageNum: this.model.pageNum
      };
      if (this.categoryType == t('common.base.degree')) model.degree = this.model.degree;
      return http.post('/event/sum/personal/list', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);

      try {
        const res = await this.fetchTableData();
        this.page = res.data;
        this.showTable = true;
      } catch (error) {
        console.log(error);
      }

      instance.hide();
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    // 时间赋值
    initDate(start, end) {
      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    initCategory(){
      category = echarts.init(document.getElementById('category'));
      category.on('click', event => {

        let seriesName = event.seriesName;
        let origin = event.data._origin;
                
        let selectType = 1;
        if(seriesName == t('common.base.finish')) selectType = 2;
        if(
          seriesName == t('common.base.satisfactionDegree.1') || 
          seriesName == t('common.base.satisfactionDegree.2') || 
          seriesName == t('common.base.satisfactionDegree.3') ||
          seriesName == t('common.base.satisfactionDegree.4') || 
          seriesName == t('common.base.satisfactionDegree.0')
        ) this.model.degree = seriesName;
        
        this.model.pageNum = 1;
        this.model.userId = origin.executor;
        this.model.timeType = selectType;

        this.renderTable()
      })

      category.on('legendselectchanged', event => {
        let arr = [];
        let opt = category.getOption();
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        if(this.categoryType == t('common.tabs.event')) {
          let sort = this.sortEventTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('common.base.degree')) {
          let sort = this.sortDegreeTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.title9')) {
          let sort = this.sortEfficiencyTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        }

        category.setOption(opt);
      })
      
    },
    chooseCategoryIgnore(value){
      this.categoryIgnoreNull = value;
      this.renderCategory();
    },
    chooseCategoryDeleted(value) {
      this.ignoreDeleted = value;
      this.renderCategory();
    },
    chooseCategoryDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    chooseCategoryTeam(value){
      this.$emit('trackEvent', 'chooseTeam');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};

      let tag = value
      this.tag = value;
      this.categoryTeamId = tag.map(item => {return item.id}).join(',');

      this.renderCategory();
      // 部门埋点
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    async renderCategory(event){
      try {
        let instance = Loading.show(this.$el);
        const res = await this.fetchCategoryData();
        
        this.categoryData = res.data;

        instance.hide();
        this.showTable = false;
      
        // this.categoryType = '事件';
        this.setCategoryOption(event);
      } catch (error) {
        console.log(error)
      }
    },
    chooseCategoryType(type){
      this.$emit('trackEvent', type);

      this.categoryType = type;
      this.setCategoryOption();
    },
    setCategoryOption(event){
      this.categoryEmpty = false;
      category && category.clear();

      let option = null;
      if(this.categoryType == t('common.tabs.event')){
        let taskOption = this.getCategoryEventOption();
        if(taskOption) option = this.getCategoryOption(taskOption);
      }

      if(this.categoryType == t('common.base.degree')){
        let degreeOption = this.getCategoryDegreeOption();
        if(degreeOption) option = this.getCategoryOption(degreeOption);
      }

      if(this.categoryType == t('report.staffCategoryChart.title9')){
        let efficiencyOption = this.getCategoryEfficiencyOption()
        if(efficiencyOption) option = this.getCategoryOption(efficiencyOption);
      }
      
      if(null == option){
        this.categoryEmpty = true;
        return
      }

      category && category.setOption(option);

      // 如果不加off事件，就会叠加触发
      category.off('legendselectchanged');
    },
    async handleStaffData(res, type){
      if(!res[type]) return res
      let types = Object.keys(res[type])
      for (let index = 0; index < types.length; index++) {
        let originItems = [res[type][types[index]]].filter(item=>item.executorStaffId)
        if(!originItems.length) continue;
        let items = originItems.map(item => {
          return {
            type: 'userName',
            id: item.executorStaffId
          }
        })

        const result = await new Promise((resolve, reject) => {
          window.WWOpenData.prefetch({ items }, (err, data) => {
            if (err) {
              return reject(err)
            }
            resolve(data)
          })
        })
        
        try {
          res[type][types[index]] = originItems.map((item, index) => {
            return Object.assign(item, { executorName: result.items[index].data })
          })[0]
        } catch (error) {
          console.warn(error)
        }
      }

      return res
    },
    fetchCategoryData(){
      const { categoryStartTime, categoryEndTime } = this
      let params = {
        createTimeStart: categoryStartTime,
        createTimeEnd: categoryEndTime,
        tagId: this.categoryTeamId,
        hide: !this.categoryIgnoreNull,
        ignoreDeleted: this.ignoreDeleted
      };
      return http.post('/event/sum/finish', params).then(async (res) =>{
        if (this.isOpenData) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          let allHandleStaffDataPromise = Object.keys(res.data).map(item =>{
            return this.handleStaffData(res.data, item)
          })
          
          await Promise.all(allHandleStaffDataPromise)
        }
        
        return res
      })
    },
    getCategoryEfficiencyOption(){
      let ctx = this;
      let time = this.categoryData.time || {};
      let data = [];
      for(let name in time){
        data.push(time[name]);
      }
      if(data.length == 0){
        this.categoryEmpty = true;
        return 
      }
      this.categoryEmpty = false;      

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均响应用时
      let atuTime = []; // 平均工作用时
      let awuTime = []; // 平均事件用时

      let maxData = 0;
      // data.sort((prev, next) => prev.AverageAcceptUsedTime - next.AverageAcceptUsedTime);
      data.forEach(item => {
        yAxisData.push(item.executorName);

        aauTime.push({
          value: item.acceptAvg, 
          _origin: item
        });

        atuTime.push({
          value: item.workAvg,
          _origin: item
        });

        awuTime.push({
          value: item.finishAvg,
          _origin: item
        });

        // if(item.acceptAvg >= maxData) maxData = parseFloat(item.acceptAvg);
        // if(item.workAvg >= maxData) maxData = parseFloat(item.workAvg);
        // if(item.finishAvg >= maxData) maxData = parseFloat(item.finishAvg);
        
        let maxAvg = Math.max(item.acceptAvg, item.workAvg, item.finishAvg, maxData); 
        if(isNaN(maxAvg)){
          return false;
        }
        maxData = maxAvg;

      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        itemStyle : { normal: {label : {show: true}}},
        data: aauTime,
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        itemStyle : { normal: {label : {show: true}}},
        data: atuTime
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        itemStyle : { normal: {label : {show: true}}},
        data: awuTime
      })

      let interval = this.computeInterval(maxData);

      let option = {
        title: t('report.statistics.title6'),
        legend: USER_EFFICIENCY_LEGEND,
        color: USER_EFFICIENCY_COLOR,
        tooltip: {
          formatter(data){
            let html = '';

            if(ctx.isOpenData) {
              let staffId = data[0].data._origin.executorStaffId
              let id = Math.ceil(Math.random() * 1000)
              html = `<ww-open-data type="userName" openid="${staffId}" id="wwOpenData${id}"></ww-open-data>`
              setTimeout(() => {
                window.WWOpenData && window.WWOpenData.bind(document.getElementById(`wwOpenData${id}`))
              }, 500);
            }else {
              let name = data[0].name;
              html += `<div>${name}</div>`;
            }

            data.forEach(item => {
              html += `<div>${item.marker} ${item.seriesName}: ${ctx.formatterTime(item.value >> 0)}</div>`;
            })

            return html;
          }
        },
        xAxis: {
          axisLabel: {
            show: true,
            formatter (value, index) {
              let temp = ctx.formatterTime(value >> 0);
              return temp == '--' ? 0 : temp;
            }
          }
        },
        yAxisData,
        series
      }

      if(interval.min != null) option.xAxis.minInterval = interval.min;
      if(interval.max != null) option.xAxis.maxInterval = interval.max;

      return option;
    },
    sortEfficiencyTable () {
      let time = this.categoryData.time || {};
      let data = [];
      for(let name in time){
        data.push(time[name]);
      }

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = []; // 平均接单用时
      let atuTime = []; // 平均工单用时
      let awuTime = []; // 平均工作用时

      let maxData = 0;

      if(this.sort == t('report.common.averageTime.0')) {
        data.sort((prev, next) => prev.acceptAvg - next.acceptAvg);
      } else if(this.sort == t('report.common.averageTime.1')) {
        data.sort((prev, next) => prev.workAvg - next.workAvg);
      } else {
        data.sort((prev, next) => prev.finishAvg - next.finishAvg);
      }
      data.forEach(item => {
        yAxisData.push(item.executorName);

        aauTime.push({
          value: item.acceptAvg, 
          _origin: item
        });

        atuTime.push({
          value: item.workAvg,
          _origin: item
        });

        awuTime.push({
          value: item.finishAvg,
          _origin: item
        });

        if(item.acceptAvg >= maxData) maxData = item.acceptAvg;
        if(item.workAvg >= maxData) maxData = item.workAvg;
        if(item.finishAvg >= maxData) maxData = item.finishAvg;
      });

      series.push({
        name: USER_EFFICIENCY_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}},
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: atuTime,
        itemStyle : { normal: {label : {show: true}}},
      })

      series.push({
        name: USER_EFFICIENCY_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        data: awuTime,
        itemStyle : { normal: {label : {show: true}}},
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryEventOption(){      
      let event = this.categoryData.event || {};
      let data = [];
      for(let name in event){
        data.push(event[name]);
      }
      if(data.length == 0){
        this.categoryEmpty = true;
        return 
      }
      this.categoryEmpty = false;
      
      let yAxisData = [];
      let createdData = [];
      let finishedData = [];
      let series = [];
      
      data.forEach(item => {
        yAxisData.push(item.executorName);
        createdData.push({
          value: item.count,
          _origin: item
        });
        finishedData.push({
          value: item.eCount,
          _origin: item
        });
      });
      
      series.push({
        name: USER_EVENT_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}},
      })

      series.push({
        name: USER_EVENT_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedData,
        itemStyle : { normal: {label : {show: true}}},
      })

      return {
        title: t('report.statistics.title5'),
        legend: USER_EVENT_LEGEND,
        color: USER_EVENT_COLOR,
        yAxisData,
        series
      }
    },
    sortEventTable () {
      let event = this.categoryData.event || {};
      let data = [];
      for(let name in event){
        data.push(event[name]);
      }

      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      if(this.sort == t('common.base.finish')) {
        data.sort((prev, next) => prev.eCount - next.eCount);
      } else {
        data.sort((prev, next) => prev.count - next.count);
      }
      data.forEach(item => {
        yAxisData.push(item.executorName);
        createdData.push({
          value: item.count,
          _origin: item
        });
        finishedDate.push({
          value: item.eCount,
          _origin: item
        });
      });

      series.push({
        name: USER_EVENT_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}},
      })

      series.push({
        name: USER_EVENT_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}},
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryDegreeOption(){
      let series = [];
      let data = [];
      let degree = this.categoryData.degree || {};
      
      for(let name in degree){
        data.push(degree[name]);
      }
      if(data.length == 0) return null;

      let yAxisData = [];
      let verySatisData = [] // 非常满意
      let satisData = [];// 满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      data.forEach(item => {
        yAxisData.push(item.executorName);
        verySatisData.push({
          value: item[ t('common.base.satisfactionDegree.0')],
          _origin: item
        });
        satisData.push({
          value: item[ t('common.base.satisfactionDegree.1')],
          _origin: item
        });
        generaldData.push({
          value: item[ t('common.base.satisfactionDegree.2')],
          _origin: item
        });
        unsatisData.push({
          value: item[ t('common.base.satisfactionDegree.3')],
          _origin: item
        });
        veryUnSatisData.push({
          value: item[ t('common.base.satisfactionDegree.4')],
          _origin: item
        });
      });

      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.statistics.title8'),
        legend: USER_DEGREE_LEGEND,
        color: USER_DEGREE_COLOR,
        yAxisData,
        series
      };
    },
    sortDegreeTable () {
      let series = [];
      let degree = this.categoryData.degree || {};
      let data = [];
      for(let name in degree){
        data.push(degree[name]);
      }

      if(data.length == 0) return null;

      let yAxisData = [];
      let verySatisData = [] // 非常满意
      let satisData = [];// 满意
      let generaldData = [];// 一般
      let unsatisData = []; // 不满意
      let veryUnSatisData = [] // 非常不满意

      data.sort((prev, next) => prev[this.sort] - next[this.sort]);

      data.forEach(item => {
        yAxisData.push(item.displayName);
        verySatisData.push({
          value: item.verySatifaction,
          _origin: item
        });
        satisData.push({
          value: item.satisfication,
          _origin: item
        });
        generaldData.push({
          value: item.general,
          _origin: item
        });
        unsatisData.push({
          value: item.unSatisfication,
          _origin: item
        });
        veryUnSatisData.push({
          value: item.veryUnSatifaction,
          _origin: item
        });
      });

      series.push({
        name: USER_DEGREE_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: verySatisData,
        itemStyle : { normal: {label : {show: true}}}
      })
      series.push({
        name: USER_DEGREE_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[2],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[3],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: unsatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_DEGREE_LEGEND[4],
        type: 'bar',
        barMaxWidth: '30px',
        stack: t('common.base.degree'),
        data: veryUnSatisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        yAxisData,
        series
      };
    },
    getCategoryOption(option){
      let that = this
      let yAxisData = option.yAxisData;
      let originObj = {}
      let originColor = []
      if(this.categoryType ==t('common.tabs.event')) {
        originObj = USER_EVENT_OBJ
        originColor = USER_EVENT_COLOR
      }else if(this.categoryType == t('common.base.degree')){
        originObj = USER_DEGREE_OBJ
        originColor = USER_DEGREE_COLOR
      }else if(this.categoryType == t('report.staffCategoryChart.title9')){
        originObj = USER_EFFICIENCY_OBJ
        originColor = USER_EFFICIENCY_COLOR
      }
      let start = 0;
      let end = yAxisData.length - 1;
      if(yAxisData.length > 10) start = end - 9;

      let _option = {
        color: option.color,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            let staffId = params[0].data._origin.executorStaffId
            let executorName = params[0].name
            let id = Math.ceil(Math.random() * 1000)

            let element = `<div id="echart-item_${id}"></div>`
            that.$nextTick(()=>{
              createVue({
                el:`#echart-item_${id}`,
                components: {
                  // [OpenDataComponent.name]: OpenDataComponent
                  'test-component': {
                    render(h) {
                      return h(
                        'div', null, [
                          isOpenData ? h('open-data', {
                            props:{
                              type:'userName',
                              openid:staffId
                            }
                          }) : null,
                          !isOpenData ? h('div', null, executorName) : null,
                          option.legend.length > 0 ?  option.legend.map((item, index) => {
                            return h('div', null, [
                                h('span', 
                                {
                                  style: {
                                    display: 'inline-block',
                                    width: '12px',
                                    height: '12px',
                                    backgroundColor: originColor[index],
                                    borderRadius: '50%',
                                    marginRight:'5px'
                                  }
                                }
                              ),
                                h('span', {style:'font-size:14px;'}, `${item}: ${params[0].data._origin[originObj[item]] || 0}`)
                              ]
                            )
                            
                          }) : null
                        ]
                      )
                    }
                  }
                },
                render(h) {
                  return (
                    <test-component />
                  )
                }
              })
              
            })
            return element;
          }
        },
        legend: {
          data: option.legend,
          top: '10px',
          left: '70px'
        },
        grid: {
          left: '20px',
          right: '60px',
          bottom: '20px',
          top: '50px',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: option.title
            }
          },
          right: 40
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            yAxisIndex: [0],
            right: '20px',
            startValue: start,
            endValue: end,
            minValueSpan: 10,
            maxValueSpan: 30
          }
        ],
        yAxis: {
          type: 'category',
          data: option.yAxisData,
          axisLabel: {
            formatter(originText) {
              if (!originText) return '';
              if(originText.length <= 7 || that.isOpenData) {
                return originText
              }
              return `${originText.slice(0, 7)}...`;
            }
          },
        },
        xAxis: {
          type: 'value'
        },
        series: option.series
      };

      if(this.categoryType == t('report.staffCategoryChart.title9') && option.tooltip) {
        _.assign(_option.tooltip, option.tooltip);
      }

      if(option.xAxis) _.assign(_option.xAxis, option.xAxis)

      return _option;
    },
    formatterTime(sec){
      // const DAY_SEC = 60 * 60 * 24;
      const HOUR_SEC = 60 * 60;
      const MIN_SEC = 60;

      // let day = sec / DAY_SEC >> 0;
      // sec = sec % DAY_SEC;

      let hour = sec / HOUR_SEC >> 0;
      sec = sec % HOUR_SEC;

      let min = sec / MIN_SEC >> 0;
      sec = sec % MIN_SEC;

      let temp = '';
      // if(day > 0) temp += day + '天';
      if(hour > 0) temp += `${hour }${t('common.base.hour')}`;
      if(min > 0) temp += `${min }${t('common.base.minute')}`;
      if(sec > 0) temp += `${sec }${t('common.base.second')}`;

      return temp ? temp : '--';
    },
    // 计算最大时间间隔
    computeInterval(sec){
      let interval = {
        min: 0,
        max: null
      }
      
      // 如果时间跨度不大于1小时
      if(sec <= 3600){
        // 以分钟为最小刻度
        interval.min = 60 ;
        // 以10分钟为最大刻度
        interval.max = 60 * 10;
        return interval;
      }

      // 如果时间跨度小于1天
      if(sec <= 3600 * 24){
        // 以小时为最小刻度
        interval.min = 3600;
        return interval;
      }

      // 如果时间跨度大于1天，则按6份划分
      let hour = sec / 3600 >> 0;
      interval.max = (hour / 6 >> 0) * 3600;
      interval.min = 3600;
      return interval
    },
    formatState (state) {
      // {"created":"待指派","allocated":"已指派","accepted":"已接受","refused":"已拒绝","processing":"进行中"}   
      let stateName = '';
      switch (state) {
      case 'created':
        stateName = t('common.task.type.created');
        break;
      case 'allocated':
        stateName = t('common.task.type.allocated');
        break;
      case 'accepted':
        stateName = t('common.task.type.accepted');
        break;
      case 'refused':
        stateName = t('common.base.usualStatus.rejected');
        break;
      case 'processing':
        stateName = t('common.task.type.processing');
        break;
      case 'finished':
        stateName = t('common.base.usualStatus.finish');
        break;
      case 'convert2Task':
        stateName = t('common.event.actionStatus.convert2Task');
        break;
      default:
        break;
      }
      return stateName;
    },
    datePicker(data) {
      // 初始化趋势图

      this.initDate(data[0], data[1]);
      // 时间埋点
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.initCategory();
    window.addEventListener('resize', _.debounce(function(){
      category.resize();
    }, 400))
  },
  watch: {
    categoryType(){
      this.showTable = false;
    }
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox,
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>

<style lang="scss">
#category{
  height: 100%;
}
.category-chart-wrap{
  width: 100%;
  height: 520px;
  position: relative;
}

.category-chart-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}
.stats-staff-category-wrap{
  //padding: 10px;
}
.el-tooltip__popper{
  max-width: 800px;
  word-break: break-all;
}
</style>

